import { NextRequest, NextResponse } from 'next/server';
import { readWords, writeWords, readCategories, generateId, readPos } from '@/lib/data';
import { verifyToken } from '@/lib/auth';
import { Word, WordSense } from '@/types';

export async function GET(request: NextRequest) {
  try {
    const categoryId = request.nextUrl.searchParams.get('categoryId');
    const words = readWords();
    
    if (categoryId) {
      const filtered = words.filter(w => w.categoryId === categoryId);
      return NextResponse.json({ success: true, words: filtered });
    }

    return NextResponse.json({ success: true, words });
  } catch (error) {
    return NextResponse.json(
      { success: false, message: '获取单词失败' },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const token = request.cookies.get('token')?.value;
    const decoded = verifyToken(token || '');
    
    if (!decoded || !decoded.isAdmin) {
      return NextResponse.json(
        { success: false, message: '需要管理员权限' },
        { status: 403 }
      );
    }

    const body = await request.json();
    const { english, chinese, phonetic, categoryId, categoryIds, senses } = body || {};

    // 只有英文是必填
    if (!english || !english.trim()) {
      return NextResponse.json(
        { success: false, message: '单词（英文）不能为空' },
        { status: 400 }
      );
    }

    // 验证分类是否存在（单个或多个）
    const categories = readCategories();
    const allIds = new Set(categories.map(c => c.id));
    let normalizedCategoryIds: string[] | undefined;
    if (Array.isArray(categoryIds) && categoryIds.length) {
      normalizedCategoryIds = Array.from(new Set(categoryIds.map(String).filter(id => allIds.has(id))));
      if (!normalizedCategoryIds.length) normalizedCategoryIds = undefined;
    } else if (categoryId && allIds.has(categoryId)) {
      normalizedCategoryIds = [categoryId];
    }

    const words = readWords();
    const validPosIds = new Set(readPos().map(p => p.id));
    let sanitizedSenses: WordSense[] | undefined = undefined;
    if (Array.isArray(senses)) {
      sanitizedSenses = senses
        .map((s: any) => ({ posId: String(s.posId || ''), definitions: Array.isArray(s.definitions) ? s.definitions.map(String).filter(Boolean) : [] }))
        .filter(s => s.posId && validPosIds.has(s.posId) && s.definitions.length > 0);
      if (sanitizedSenses.length === 0) sanitizedSenses = undefined;
    }

    // 英文唯一性校验（不区分大小写，去除首尾空格）
    const englishKey = english.trim().toLowerCase();
    const exists = words.some(w => (w.english || '').trim().toLowerCase() === englishKey);
    if (exists) {
      return NextResponse.json(
        { success: false, message: '英文单词已存在，不能重复' },
        { status: 400 }
      );
    }

    const newWord: Word = {
      id: generateId(),
      english: english.trim(),
      phonetic: phonetic?.trim() || undefined,
      chinese: chinese?.trim() || '',
      categoryId: normalizedCategoryIds?.[0] || '',
      categoryIds: normalizedCategoryIds,
      createdAt: new Date().toISOString(),
      senses: sanitizedSenses,
    };

    words.push(newWord);
    writeWords(words);

    return NextResponse.json({ success: true, word: newWord });
  } catch (error) {
    return NextResponse.json(
      { success: false, message: '添加单词失败' },
      { status: 500 }
    );
  }
}

export async function PATCH(request: NextRequest) {
  try {
    const token = request.cookies.get('token')?.value;
    const decoded = verifyToken(token || '');
    if (!decoded || !decoded.isAdmin) {
      return NextResponse.json(
        { success: false, message: '需要管理员权限' },
        { status: 403 }
      );
    }

    const { ids, op, categoryIds } = await request.json();
    if (!Array.isArray(ids) || ids.length === 0) {
      return NextResponse.json({ success: false, message: '缺少要操作的单词ID' }, { status: 400 });
    }
    const words = readWords();
    const idSet = new Set(ids as string[]);
    const categories = readCategories();
    const allIds = new Set(categories.map(c => c.id));
    const validCats = Array.isArray(categoryIds) ? Array.from(new Set(categoryIds.map(String).filter(id => allIds.has(id)))) : [];

    let affected = 0;
    for (const w of words) {
      if (!idSet.has(w.id)) continue;
      const current = Array.isArray(w.categoryIds) ? [...w.categoryIds] : (w.categoryId ? [w.categoryId] : []);
      let next = current;
      if (op === 'replace') {
        next = [...validCats];
      } else if (op === 'add') {
        const set = new Set(current);
        validCats.forEach(id => set.add(id));
        next = Array.from(set);
      } else if (op === 'remove') {
        const rm = new Set(validCats);
        next = current.filter(id => !rm.has(id));
      } else if (op === 'clear') {
        next = [];
      } else {
        return NextResponse.json({ success: false, message: '未知操作' }, { status: 400 });
      }
      w.categoryIds = next.length ? next : undefined;
      w.categoryId = next[0] || '';
      affected++;
    }
    writeWords(words);
    return NextResponse.json({ success: true, affected });
  } catch (error) {
    return NextResponse.json(
      { success: false, message: '批量更新分类失败' },
      { status: 500 }
    );
  }
}

export async function DELETE(request: NextRequest) {
  try {
    const token = request.cookies.get('token')?.value;
    const decoded = verifyToken(token || '');
    if (!decoded || !decoded.isAdmin) {
      return NextResponse.json(
        { success: false, message: '需要管理员权限' },
        { status: 403 }
      );
    }

    let ids: string[] = [];
    try {
      const body = await request.json();
      ids = Array.isArray(body?.ids) ? body.ids.filter((x: any) => typeof x === 'string') : [];
    } catch {}

    if (!ids.length) {
      return NextResponse.json(
        { success: false, message: '缺少要删除的单词ID' },
        { status: 400 }
      );
    }

    const before = readWords();
    const idSet = new Set(ids);
    const after = before.filter(w => !idSet.has(w.id));
    writeWords(after);
    return NextResponse.json({ success: true, deleted: before.length - after.length });
  } catch (error) {
    return NextResponse.json(
      { success: false, message: '批量删除单词失败' },
      { status: 500 }
    );
  }
}

